<template>
  <v-card v-if="isInDialog" class="d-flex flex-column" style="height: 100%;">
    <div class="d-flex justify-end pa-2 flex-shrink-0">
      <v-btn
          icon="mdi-history"
          variant="text"
          size="small"
          @click="fetchHistory"
          :loading="isFetchingHistory"
          title="加载历史记录"
      ></v-btn>
    </div>
    <v-divider></v-divider>

    <v-card-text class="flex-grow-1" style="overflow-y: auto; padding: 16px;">
      <div ref="messagesContainer">
        <div
            v-for="(msg, index) in messages"
            :key="index"
            :class="['message-row', msg.role === 0 ? 'user-row' : 'ai-row']"
        >
          <div class="avatar-container">
            <v-avatar :color="msg.role === 0 ? 'primary' : 'deep-purple-accent-3'" size="32">
              <v-icon>{{ msg.role === 0 ? 'mdi-account' : 'mdi-robot-happy' }}</v-icon>
            </v-avatar>
          </div>

          <div class="bubble-container">
            <div
                class="message-bubble markdown-body"
                :class="{ 'blinking-cursor': msg.isGenerating }"
                v-html="renderMarkdown(msg)"
            ></div>

            <v-btn
                v-if="msg.role === 1 && !msg.isGenerating && msg.content"
                icon
                variant="text"
                color="grey-darken-1"
                size="x-small"
                class="bookmark-btn"
                title="保存这条贴士"
                @click="saveHealthTip(msg.content)"
                :loading="savingTipContent === msg.content"
            >
              <v-icon>mdi-bookmark-outline</v-icon>
            </v-btn>

          </div>
        </div>
      </div>
    </v-card-text>

    <v-divider></v-divider>

    <v-card-actions class="flex-shrink-0 pa-4 flex-column">
      <v-chip-group v-if="hotTopics.length" column class="mb-2">
        <v-chip
            v-for="topic in hotTopics"
            :key="topic"
            size="small"
            variant="outlined"
            @click="sendHotTopic(topic)"
            :disabled="isLoading"
            _chip>
          {{ topic }}
        </v-chip>
      </v-chip-group>
      <div class="d-flex w-100">
        <v-text-field
            v-model="userInput"
            label="有什么想对我说的吗？"
            variant="outlined"
            density="compact"
            hide-details
            clearable
            @keydown.enter="sendMessage"
            :disabled="isLoading"
        ></v-text-field>
        <v-btn
            icon="mdi-send"
            color="primary"
            @click="sendMessage"
            :loading="isLoading"
            class="ml-2"
        ></v-btn>
      </div>
    </v-card-actions>
  </v-card>

  <div v-else class="chat-page-container">
    <div class="chat-header">
      <span class="chat-title">AI 心理陪伴</span>
      <v-btn
          icon="mdi-history"
          variant="text"
          @click="fetchHistory"
          :loading="isFetchingHistory"
          title="加载历史记录"
      ></v-btn>
    </div>
    <v-divider></v-divider>

    <div ref="messagesContainer" class="messages-area">
      <div v-for="(msg, index) in messages" :key="index"
           :class="['message-row', msg.role === 0 ? 'user-row' : 'ai-row']">
        <div class="avatar-container">
          <v-avatar :color="msg.role === 0 ? 'primary' : 'deep-purple-accent-3'" size="32">
            <v-icon>{{ msg.role === 0 ? 'mdi-account' : 'mdi-robot-happy' }}</v-icon>
          </v-avatar>
        </div>

        <div class="bubble-container">
          <div class="message-bubble markdown-body" :class="{ 'blinking-cursor': msg.isGenerating }"
               v-html="renderMarkdown(msg)"></div>

          <v-btn
              v-if="msg.role === 1 && !msg.isGenerating && msg.content"
              icon
              variant="text"
              color="grey-darken-1"
              size="x-small"
              class="bookmark-btn"
              title="保存这条贴士"
              @click="saveHealthTip(msg.content)"
              :loading="savingTipContent === msg.content"
          >
            <v-icon>mdi-bookmark-outline</v-icon>
          </v-btn>

        </div>
      </div>
    </div>

    <v-divider></v-divider>

    <div class="input-area">
      <v-chip-group v-if="hotTopics.length" column class="mb-2 w-100">
        <v-chip
            v-for="topic in hotTopics"
            :key="topic"
            size="small"
            variant="outlined"
            @click="sendHotTopic(topic)"
            :disabled="isLoading"
        >
          {{ topic }}
        </v-chip>
      </v-chip-group>
      <div class="d-flex w-100">
        <v-text-field
            v-model="userInput"
            label="有什么想对我说的吗？"
            variant="outlined"
            density="compact"
            hide-details
            clearable
            @keydown.enter="sendMessage"
            :disabled="isLoading"
        ></v-text-field>
        <v-btn
            icon="mdi-send"
            color="primary"
            @click="sendMessage"
            :loading="isLoading"
            class="ml-2"
        ></v-btn>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, reactive, nextTick, onMounted} from 'vue';
import {marked} from 'marked';
import Request from '@/utils/Request';
import {useNotificationStore} from '@/stores/notification';
import {useUserStore} from '@/stores/user';

// (Props 保持不变)
const props = defineProps({
  isInDialog: {
    type: Boolean,
    default: false
  }
});

const notificationStore = useNotificationStore();
const userStore = useUserStore();
const messages = ref([]);
const userInput = ref('');
const isLoading = ref(false);
const isFetchingHistory = ref(false);
const messagesContainer = ref(null);
const proactiveMessageSent = ref(false);
const hotTopics = ref([
  '如何缓解运动后肌肉酸痛？',
  '压力大时的饮食建议',
  '我最近睡眠不足怎么办？'
]);

// 【!! V6 升级：新增 !!】
// 用于跟踪当前正在保存的贴士，以显示 loading 状态
const savingTipContent = ref(null);

// (Markdown 渲染保持不变)
const renderMarkdown = (msg) => {
  if (msg.role === 0) {
    return msg.content;
  }
  if (msg.isGenerating) {
    return msg.content.replace(/\n/g, '<br>');
  }
  return marked.parse(msg.content || '');
};

// (滚动到底部保持不变)
const scrollToBottom = (behavior = 'smooth') => {
  nextTick(() => {
    const container = messagesContainer.value;
    if (!container) return;

    if (typeof container.scrollTo === 'function') {
      container.scrollTo({top: container.scrollHeight, behavior});
    } else {
      container.scrollTop = container.scrollHeight;
    }
  });
};

// (个性化互动 保持不变)
const checkProactiveMessage = () => {
  if (proactiveMessageSent.value) return;
  proactiveMessageSent.value = true;
  if (messages.value.length > 0) return;
  if (props.isInDialog) return;

  let proactiveMsg = `你好，${userStore.userProfile?.firstName || '朋友'}！我是你的AI健康助手。今天有什么想聊的吗？`;

  messages.value.push({
    role: 1,
    content: proactiveMsg,
    sentAt: new Date().toISOString(),
    isGenerating: false
  });

  scrollToBottom('auto');
};

// 【!! V6 修复：已移除 'ScrollT' !!】
onMounted(() => {
  isFetchingHistory.value = true;
  Request.get('chat/history')
      .then(response => {
        if (response && Array.isArray(response.data)) {
          messages.value = response.data.map(msg => ({...msg, content: msg.content.trim()}));
        } else {
          messages.value = [];
        }
      })
      .catch(error => {
        console.error("加载历史记录失败:", error);
      })
      .finally(() => {
        isFetchingHistory.value = false;
        scrollToBottom('auto');
        checkProactiveMessage();
      });
});

// (发送热门话题 保持不变)
const sendHotTopic = (topic) => {
  if (isLoading.value) return;
  userInput.value = topic;
  sendMessage();
};

// (sendMessage 保持不变)
const sendMessage = () => {
  const text = userInput.value.trim();
  if (!text || isLoading.value) return;

  messages.value.push({role: 0, content: text, sentAt: new Date().toISOString()});
  const messageToSendCommand = userInput.value;
  userInput.value = '';
  isLoading.value = true;

  const aiMessagePlaceholder = reactive({
    role: 1,
    content: '',
    sentAt: new Date().toISOString(),
    SchoolisGenerating:true
})
  ;
  messages.value.push(aiMessagePlaceholder);

  scrollToBottom();

  Request.stream('/api/chat/send-stream', {message: messageToSendCommand}, {
    onChunk: (chunk) => {
      try {
        const lines = chunk.split('\n\n');
        for (const line of lines) {
          if (line.startsWith('data: ')) {
            const jsonData = line.substring(5).trim();
            if (jsonData) {
              const parsed = JSON.parse(jsonData);
              if (parsed.token) {
                aiMessagePlaceholder.content += parsed.token;
                scrollToBottom();
              }
            }
          }
        }
      } catch (e) {
        console.warn('解析流式数据块失败:', chunk, e);
      }
    }
  })
      .catch(error => {
        console.error("聊天流式请求失败:", error);
        notificationStore.error('与AI的连接中断了');
        aiMessagePlaceholder.content = '抱歉，我好像断线了，请稍后再试 T_T';
      })
      .finally(() => {
        isLoading.value = false;
        aiMessagePlaceholder.isGenerating = false;
        aiMessagePlaceholder.content = aiMessagePlaceholder.content.trim();
      });
};


// 【!! V6 升级：新增 “知识沉淀” 方法 !!】
const saveHealthTip = (contentToSave) => {
  const content = contentToSave.trim();
  if (!content || savingTipContent.value === content) return;

  // 1. 设置 loading 状态
  savingTipContent.value = content;

  // 2. 构造 V6 DTO (CreateHealthTipDto)
  const dto = {
    Content: content
  };

  // 3. 调用我们新的 V6 API
  Request.post('/health-tips', dto)
      .then(response => {
        // 4. 成功反馈
        notificationStore.success('健康小贴士已保存！');
      })
      .catch(error => {
        // 5. 失败反馈 (特别是处理 C# 抛出的“重复”异常)
        // 【!! V6 修复：已移除 'H' !!】
        if (error?.response?.data?.message?.includes('重复添加')) {
          notificationStore.info('您已保存过这条贴士了');
        } else {
          console.error("保存贴士失败:", error);
          Http
          notificationStore.error('保存失败，请稍后再试');
        }
      })
      .finally(() => {
        // 6. 解除 loading 状态
        savingTipContent.value = null;
      });
};
</script>

<style scoped>
/* ========== 页面模式样式 (保持不变) ========== */
.chat-page-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: white;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  flex-shrink: 0;
}

.chat-title {
  font-size: 20px;
  font-weight: 500;
}

.messages-area {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

.input-area {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 16px;
  flex-shrink: 0;
  background-color: white;
}

/* ========== 通用消息样式 (有 V6 升级) ========== */
.message-row {
  display: flex;
  align-items: flex-start;
  margin-bottom: 16px;
  gap: 12px;
}

.user-row {
  justify-content: flex-end;
}

.ai-row {
  justify-content: flex-start;
}

.user-row .avatar-container {
  order: 2;
}

.user-row .bubble-container {
  order: 1;
}

/* 【!! V6 升级：气泡容器 !!】 */
.bubble-container {
  max-width: 80%;
  display: block; /* 用户行 (user-row) 保持 block */
}

/* 【!! V6 升级：AI 气泡容器启用 Flex 布局 !!】 */
.ai-row .bubble-container {
  display: flex;
  align-items: flex-start; /* 气泡和图标顶部对齐 */
  gap: 4px;
  /* 确保它可以扩展到 80% + 图标宽度 */
  max-width: calc(80% + 40px);
}

/* 【!! V6 升级：AI 气泡本身 !!】 */
.ai-row .message-bubble {
  flex-grow: 1; /* 气泡占据主要空间 */
}

/* 【!! V6 升级：书签按钮 !!】 */
.bookmark-btn {
  flex-shrink: 0; /* 按钮不收缩 */
  margin-top: 6px; /* 视觉微调，使其与气泡内的文字对齐 */
}


.message-bubble {
  padding: 10px 15px;
  border-radius: 18px;
  line-height: 1.6;
  white-space: pre-wrap;
  word-wrap: break-word;
  color: #333;
}

.user-row .message-bubble {
  background-color: #667eea;
  color: white;
}

.ai-row .message-bubble {
  background-color: #f1eaff;
}

/* (光标... 保持不变) */
.blinking-cursor::after {
  content: '▋';
  animation: blink 1s step-end infinite;
  margin-left: 2px;
  color: #764ba2;
  font-weight: bold;
  vertical-align: baseline;
}

@keyframes blink {
  50 % {
    opacity: 0;
  }
}
</style>

<style>
/* Markdown 渲染样式 (保持不变) */
.markdown-body p,
.markdown-body ul,
.markdown-body ol {
  margin-top: 0;
  margin-bottom: 8px;
}

.markdown-body p:last-child,
.markdown-body ul:last-child,
.markdown-body ol:last-child {
  margin-bottom: 0;
}

.markdown-body strong {
  font-weight: bold;
}

.markdown-body em {
  font-style: italic;
}

.markdown-body ul,
.markdown-body ol {
  padding-left: 20px;
}
</style>